const expres=require('express')
const utils=require('utility')
const Router=expres.Router()
const model=require('./model')

const KindTable=model.getModel('kind_table')
const TokenTable=model.getModel('token_table')

const _filter={'pwd':0,'__v':0}

Router.get('/list',(req,res)=>{
  const token=req.header('token')
  TokenTable.findOne({token},function(e,d){
    if(!d){
      return res.json({code:1,msg:'token已失效'})
    }

    KindTable.find({},function(e1,d1){
      return res.json({code:0, data:d1})
    })
  })
})

Router.post('/delete',(req,res)=>{
  const {_id}=req.body
  const token=req.header('token')

  TokenTable.findOne({token},function(e,d){
    if(!d){
      return res.json({code:1,msg:'token已失效'})
    }
    KindTable.remove({_id},(err)=>{
      if(err){
        return res.json({code:1,msg:'删除失败'})
      }
      return res.json({code:0,msg:'删除成功'})
    })
  })
})

Router.post('/create',(req,res)=>{
  const {name}=req.body

  const token=req.header('token')

  TokenTable.findOne({token},function(e,d){
    if(!d){
      return res.json({code:1,msg:'token已失效'})
    }

    const kindModel=new KindTable({name})
    kindModel.save((e,d)=>{
      if(e){
        return res.json({code:1,msg:'后端出错了'})
      }
      return res.json({code:0,data:{d}})
    })
  })
})

Router.post('/edit',(req,res)=>{
  const {_id,name}=req.body

  const token=req.header('token')

  TokenTable.findOne({token},function(e,d){
    if(!d){
      return res.json({code:1,msg:'token已失效'})
    }
    KindTable.findOneAndUpdate({_id},{name},function(e1,d1){
      if(e1){
        return res.json({code:1,msg:'后端出错了'})
      }
      return res.json({code:0,data:d1})
    })
  })
})

module.exports=Router
